import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { LoginResult } from '@/types/member'

export const useMemberStore = defineStore(
  'member',
  () => {
    // Define profile with an initial value
    const profile = ref<LoginResult | undefined>({} as LoginResult)

    // Update setProfileField to check for an undefined profile
    const setProfileField = (field: keyof LoginResult, value: any) => {
      if (!profile.value) {
        profile.value = {} as LoginResult // Initialize profile if undefined
      }
      profile.value[field] = value
    }
    const getProfileField = (field: keyof LoginResult) => {
      return profile.value?.[field]
    }

    // 清除人员信息
    const clearProfile = () => {
      profile.value = undefined
    }

    return {
      profile,
      setProfileField,
      getProfileField,
      clearProfile,
    }
  },
  {
    persist: {
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
